<template>
  <div class="common-layout questionIndex">
    <!-- container-xl containermain bg-white -->
    <el-container class="container-box">
      <el-container class="container-left">
        <el-header class="container-header">
          <el-tabs
            id="p20"
            type="border-card"
            :stretch="stretch"
            v-model="activeName"
            @tab-change="tabChange"
          >
            <el-tab-pane
              :lazy="true"
              :name="TABSNAME.public"
              label="公开题库"
            ></el-tab-pane>
            <!-- <el-tab-pane :lazy="true" :name="TABSNAME.team" label="团队题库"></el-tab-pane>
            <el-tab-pane :lazy="true" :name="TABSNAME.codeforces" label="RemoteJudge"></el-tab-pane>
            <el-tab-pane :lazy="true" v-if="vip" :name="TABSNAME.match" label="精选题库"></el-tab-pane> -->
            <!-- <el-tab-pane :lazy="true" :name="TABSNAME.user" label="我的题库"></el-tab-pane> -->
            <!-- 搜索条件 -->
            <div class="">
              <el-form class="container-header-form" label-position="left">
                <div v-if="tabsCfg[activeName].desc">
                  <div>
                    <el-text size="small" type="info">
                      <el-icon>
                        <InfoFilled />
                      </el-icon>
                      {{ tabsCfg[activeName].desc }}
                    </el-text>
                  </div>
                </div>
                <el-form-item
                  v-if="activeName == TABSNAME.codeforces"
                  class="container-header-form-item"
                  size="default"
                  label="题库筛选"
                  :label-width="70"
                >
                  <el-radio-group size="default">
                    <el-button
                      class=""
                      :plain="false"
                      type="primary"
                      size="default"
                    >
                      CODEFORCES
                    </el-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="activeName == TABSNAME.match"
                  class="container-header-form-item"
                  size="default"
                  label="题库来源"
                  :label-width="70"
                >
                  <el-radio-group size="default">
                    <el-button
                      @click="formInline.source = ''"
                      :type="!Boolean(formInline.source) ? 'primary' : 'info'"
                      :plain="!Boolean(formInline.source) ? false : true"
                      size="default"
                    >
                      全部
                    </el-button>
                    <el-button
                      v-for="(value, key) in DATAform"
                      @click="sourceClick(value)"
                      :type="formInline.source === value ? 'primary' : 'info'"
                      :plain="formInline.source === value ? false : true"
                      :key="key"
                      size="default"
                    >
                      {{ key }}
                    </el-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  class="container-header-form-item"
                  size="default"
                  label="难度筛选"
                  prop="rating"
                  :label-width="70"
                >
                  <!-- CF 难度 -->
                  <div
                    v-if="
                      activeName == TABSNAME.match &&
                      formInline.source == DATAform.CODEFORCES
                    "
                  >
                    <el-select
                      id="rating"
                      v-model="formInline.rating"
                      filterable
                      clearable
                      placeholder="选择难度"
                      style="width: 250px"
                    >
                      <el-option
                        v-for="(item, key) in CFdifficulty.length"
                        :key="item"
                        :label="`*${key * 100 + CFdifficulty.start}`"
                        :value="`${key * 100 + CFdifficulty.start}`"
                      />
                    </el-select>
                  </div>
                  <div v-else>
                    <el-button
                      @click="formInline.difficulty = []"
                      :type="
                        !Boolean(formInline.difficulty?.length)
                          ? 'primary'
                          : 'info'
                      "
                      :plain="
                        !Boolean(formInline.difficulty?.length) ? false : true
                      "
                      size="default"
                    >
                      全部
                    </el-button>
                    <el-button
                      @click="formDifficultyclick(key)"
                      :type="
                        formInline.difficulty?.includes(key)
                          ? 'primary'
                          : 'info'
                      "
                      :plain="
                        formInline.difficulty?.includes(key) ? false : true
                      "
                      v-for="(item, key) in DATAdifficulty"
                      :key="item"
                      size="default"
                    >
                      {{ item }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item
                  class="container-header-form-item"
                  size="default"
                  label="查找题目"
                  :label-width="70"
                >
                  <div class="container-header-form-item-flex">
                    <div>
                      <el-input
                        size=""
                        :style="{ width: '250px' }"
                        v-model.lazy="formInline.name"
                        placeholder="输入题目名或ID搜索"
                      >
                      </el-input>
                      <el-button
                        class="container-header-form-search-btn"
                        @click="start"
                        type="primary"
                        size="default"
                      >
                        搜索
                      </el-button>
                    </div>
                    <router-link
                      v-if="activeName == TABSNAME.user && getuser?.isAdmin"
                      custom
                      :to="{ name: '修改我的题库' }"
                      v-slot="{ navigate }"
                    >
                      <el-button @click="navigate" type="primary" size="default"
                        >+ 创建我的题目</el-button
                      >
                    </router-link>
                    <div v-if="activeName == TABSNAME.team && getuser?.isAdmin">
                      <el-button
                        size="default"
                        @click="dialogVisibleAddQuestion = true"
                        type="primary"
                      >
                        + 导入团队题目
                      </el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-tabs>
        </el-header>
        <el-main class="container-content">
          <!-- <el-scrollbar> -->
          <el-table
            height="90vh"
            row-class-name="cursor-pointer"
            :data="questionData"
            stripe
            v-loading="loading"
            width="100%"
            @row-click="rowClick"
            @sort-change="sortChange"
          >
            <template v-slot:empty>
              <el-empty
                image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
              />
            </template>
            <el-table-column width="60" prop="date" label="状态">
              <template #default="{ row }">
                <el-icon
                  :color="
                    Number(row.myACcount)
                      ? 'var(--color-cheng)'
                      : 'var(--color-43)'
                  "
                >
                  <Select v-if="Number(row.myACcount)" />
                  <CloseBold v-else-if="Number(row.myUNcount)" />
                  <SemiSelect v-else />
                </el-icon>
              </template>
            </el-table-column>
            <el-table-column
              width="90"
              prop="ID"
              show-overflow-tooltip
              label="题号"
            />
            <el-table-column width="60" prop="type" label="题型" />
            <el-table-column
              width=""
              min-width="200"
              show-overflow-tooltip
              prop="name"
              label="题目"
            />
            <el-table-column width="300" prop="questionlabel" label="知识点">
              <template #default="{ row, column }">
                <el-tag
                  class="question-intable-label"
                  text
                  type="primary"
                  effect="plain"
                  size="default"
                  v-for="(vo, keys) in row.questionlabel"
                  v-text="getlabel.find((e) => e.ID === vo.labelid)?.name"
                  :key="`1-${keys}`"
                  @click.stop="setlabelId(vo.labelid)"
                >
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              width="150"
              show-overflow-tooltip
              prop="difficulty"
              label="难度"
            >
              <template #default="{ row, column }">
                <div
                  v-if="row.difficulty"
                  :class="`difficulty-${row.difficulty}`"
                >
                  {{ row.difficulty ? DATAdifficulty[row.difficulty] : "" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              width="100"
              prop="ACcount"
              v-if="activeName !== TABSNAME.match"
              label="AC次数"
            >
              <template #default="{ row }">
                {{ row.ACcount || 0 }}
              </template>
            </el-table-column>
            <el-table-column
              width="100"
              prop="userquestioncount"
              v-if="activeName !== TABSNAME.match"
              label="提交次数"
            >
              <template #default="{ row }">
                {{ row.userquestioncount || 0 }}
              </template>
            </el-table-column>
            <el-table-column
              width=""
              min-width="100"
              v-if="activeName !== TABSNAME.match"
              label="AC率"
            >
              <template #default="{ row, column }">
                <el-progress
                  :text-inside="true"
                  :stroke-width="18"
                  :percentage="getACRate(row)"
                  :color="customColors"
                />
              </template>
            </el-table-column>
            <el-table-column
              width=""
              v-if="
                activeName == TABSNAME.match &&
                formInline.source == DATAform.CODEFORCES
              "
              show-overflow-tooltip
              prop="rating"
              label="Rating"
              sortable="custom"
            >
            </el-table-column>
            <el-table-column
              v-if="activeName == TABSNAME.match"
              width=""
              show-overflow-tooltip
              prop="dataform"
              label="来源"
            >
              <template #default="{ row, column }">
                <el-link
                  v-if="formInline.source == DATAform.CODEFORCES"
                  @click.navite.stop="() => {}"
                  :href="getCfQuestionUrl(row.dataform)"
                  target="_blank"
                  type="primary"
                >
                  {{ row.dataform }}
                </el-link>
                <span v-else>
                  {{ row.dataform }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              width="160"
              prop=""
              v-if="activeName === 'user'"
              label="操作"
            >
              <template #default="{ row, column }">
                <router-link
                  custom
                  :to="{ name: '修改我的题库', query: { ID: row.ID } }"
                  v-slot="{ navigate }"
                >
                  <el-button
                    size="default"
                    type="primary"
                    @click.stop="navigate"
                    >编辑</el-button
                  >
                </router-link>
                <el-button
                  size="default"
                  type="primary"
                  @click.stop="del(row.ID)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            class="pager"
            size="default"
            :page-size="limit"
            :page-sizes="pageSizes"
            :total="totalCount"
            layout="total, sizes, prev, pager, next"
            @current-change="changePage"
            @size-change="handleSizeChange"
            :current-page="Math.floor(offset / limit) + 1"
          >
          </el-pagination>
          <!-- </el-scrollbar> -->
        </el-main>
      </el-container>
      <el-aside class="container-aside">
        <selectlabelVue
          @update:label="grouplabelclick"
          @change:label="groupLabelClose"
          @clear:label="groupLabelClear"
          :label="setlabel"
          :search="start"
        ></selectlabelVue>
      </el-aside>
    </el-container>
    <!-- 添加团队题目 -->
    <el-dialog
      v-model="dialogVisibleAddQuestion"
      v-if="dialogVisibleAddQuestion"
      title="选择题目"
      width="840px"
      height="90vh"
      top="0"
      :before-close="beforeClose"
    >
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          选择题目
        </span>
      </template>
      <selectquestionVue
        :addclick="addclick"
        :teamid="teamId"
      ></selectquestionVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { CloseBold, Select, SemiSelect } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, TabPaneName } from "element-plus";
import { debounce } from "underscore";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  Iobj,
  Iquestionoption,
  asyncaddquestionteam,
  asyncdelquestion,
  asyncselectquestion,
} from "../../api";
import { Iquestion, Storekey } from "../../interface";
import Studycodemodel from "../../mysql_interface/studycodemodel";
import selectlabelVue from "../../ojSass/components/selectlabel/aside.vue";
import selectquestionVue from "../../ojSass/components/selectquestion/question.vue";
import { CFdifficulty, DATAform } from "../../ojSass/data/data";
import { DATAdifficulty } from "../../index/data/data";
enum TABSNAME {
  public = "public",
  team = "team", // team
  match = "match",
  codeforces = "codeforces",
  user = "user",
}
const tabsCfg = {
  [TABSNAME.public]: {
    desc: "公开题库：该专题是系统公开题库，所有人都可以访问",
  },
  [TABSNAME.team]: {
    desc: "团队题库：该题库是团队内部指定题库，由团队管理员从“我的专题”中授权开放至团队",
  },
  [TABSNAME.match]: {
    desc: "精选题库：该题库只有团队管理员可见，可将该题库中的题目添加到“我的题目”",
  },
  [TABSNAME.codeforces]: {
    desc: "初试专题：适合CSP/NOIP第一轮的初试题目，以知识点分类汇总",
  },
  [TABSNAME.user]: {
    desc: "我的题目：用于我个人收藏的题目。如果是团队管理员，可以将我的题目开放至团队",
  },
};

// AC 率颜色
const customColors = [
  { color: "#e83828", percentage: 20 },
  { color: "#f0830ac", percentage: 40 },
  { color: "#82bd1c", percentage: 60 },
  { color: "#1ecbb4", percentage: 70 },
  { color: "#4683fa", percentage: 100 },
];
const router = useRouter();
const store = useStore(Storekey);

const getuser = computed(() => {
  return store.state.user;
});
const teamId = computed(() => {
  return Number(getuser.value?.teamid);
});
const getteam = computed(() => {
  return store.state.team?.rows || [];
});
const getlabel = computed(() => {
  return store.state.label?.rows || [];
});
const vip = computed(() => {
  return getuser.value?.uservip?.find((c) => c.viplistid === 1);
});

const formInline = reactive<
  Iobj<Studycodemodel.Iquestion & { ratingSort: string }>
>({
  teamid: getteam.value.map((e) => e.ID),
  name: "",
  // label: "",
  ratingSort: "ASC",
});
const loading = ref(true);

const setlabel = ref<number[]>([]);
function setlabelId(labelId?: number) {
  if (labelId) {
    setlabel.value.splice(0, setlabel.value.length, labelId);
  }
}
function grouplabelclick(item: number) {
  const i = setlabel.value.findIndex((e) => e === item);
  if (i != -1) {
    setlabel.value.splice(i, 1);
  } else {
    setlabel.value.push(item);
  }
}
function groupLabelClose(i: number) {
  setlabel.value.splice(i, 1);
}
function groupLabelClear() {
  // 响应式数组清空
  setlabel.value.length = 0;
}
watch(setlabel.value, () => {
  start();
});

const route = useRoute();
const routeQuery = computed(() => {
  return route.query as Record<string, string>;
});
const order = computed(() => {
  return (routeQuery.value.order ||
    "ID") as string as keyof Studycodemodel.Iquestion;
});
const offset = ref(0);
const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500];
const sortable = computed(() => {
  return (routeQuery.value.sortable || "ASC") as "DESC" | "ASC";
});

function reset() {
  formInline.name = undefined;
  formInline.difficulty = undefined;
  formInline.rating = undefined;
  formInline.source = undefined;
  // 响应式数组清空
  setlabel.value.length = 0;
  //
  offset.value = 0;
  limit.value = 20;
  start();
}
const stretch = ref(false);
const activeName = ref<TABSNAME>(TABSNAME.public);
function tabChange(v: TabPaneName) {
  reset();
  router.push({ query: { tabName: v } });
}

// AC率
function getACRate(row: Iquestion) {
  return row.userquestioncount
    ? Math.floor(
        (Number(row.ACcount || 0) / Number(row.userquestioncount)) * 100
      )
    : 0;
}
function getCfQuestionUrl(v: string = "") {
  v = v || "";
  let url = "https://codeforces.com/problemset/problem";
  let str = v.split("-")[0].replace("CF", "");
  let path1 = str.slice(0, str.length - 1);
  let path2 = str.slice(str.length - 1);
  return `${url}/${path1}/${path2}`;
}
// 表格点击跳转
function rowClick(row: any, column: any, event: Event) {
  router.push({
    name: "题目",
    params: { ID: row.ID },
    query: {
      order: order.value,
      offset: offset.value,
      limit: limit.value,
      teamid:
        activeName.value === TABSNAME.team
          ? formInline.teamid.length
            ? formInline.teamid
            : getteam.value?.map((v) => v.ID)
          : null,
      // 搜索条件
      name: formInline.name,
      range:
        activeName.value === TABSNAME.team ? TABSNAME.public : activeName.value,
      setlabel: setlabel.value,
      difficulty: formInline.difficulty,
      rating: formInline.rating,
      source: formInline.source,
      userid: activeName.value === TABSNAME.user ? getuser.value?.ID : null,
    },
  });
}
// 排序
function sortChange(data: {
  column: any;
  prop: string;
  order: "ascending" | "descending" | null;
}) {
  let sort = data.order === "descending" ? "DESC" : "ASC";
  formInline.ratingSort = sort;
}

watch(formInline, () => {
  start();
});
const debouncet1 = ref<Function>();

const tabName = computed(() => {
  return (route.query.tabName as TABSNAME) || TABSNAME.public;
});
watch(tabName, (n, o) => {
  activeName.value = TABSNAME[tabName.value];
});

onMounted(() => {
  // 是否跳转
  if (tabName.value) {
    activeName.value = TABSNAME[tabName.value];
  }
  store.dispatch("actionlabel");
  debouncet1.value = debouncet();
  start();
});

const questionData = ref<Studycodemodel.Iquestion[]>([]);
const totalCount = ref(0);
function debouncet() {
  return debounce(async () => {
    const { name, teamid, ratingSort } = formInline;
    const obj: Iobj<Iquestionoption> = {
      _order: ["rating", order.value],
      _sortable: ratingSort ? ratingSort : sortable.value || "ASC",
      _offset: offset.value,
      _limit: limit.value,
      type: "代码",
    };
    let _like: [keyof Studycodemodel.Iquestion, any];
    if (name) {
      _like = ["name", formInline.name];
      const id = Number(name);
      if (id == name) {
        _like = ["ID", id];
      }
      obj._like = _like;
    }
    let t;
    // 公开题库
    if (activeName.value === TABSNAME.public) {
      obj.range = TABSNAME.public;
      //
    } else if (activeName.value === TABSNAME.codeforces) {
      obj.range = TABSNAME.codeforces;
      // 精选题库
    } else if (activeName.value === TABSNAME.match) {
      obj.range = TABSNAME.match;
      // 来源 dataform 中模糊匹配的是 cf Rating
      if (formInline.rating) {
        obj.rating = formInline.rating;
      }
      if (formInline.source) {
        obj.source = formInline.source;
      }
      //
    } else if (activeName.value === TABSNAME.user) {
      obj.range = TABSNAME.user;
      obj.userid = getuser.value?.ID;
    } else {
      t = teamid.length ? teamid : getteam.value?.map((v) => v.ID);
      obj.teamid = t;
    }
    if (!obj.range) {
      obj.range = TABSNAME.public;
    }
    if (
      formInline.source != DATAform.CODEFORCES &&
      Array.isArray(formInline.difficulty) &&
      formInline.difficulty.length
    ) {
      obj.difficulty = formInline.difficulty;
    }
    if (setlabel.value && setlabel.value.length) {
      if (!obj._include) obj._include = {};
      obj._include.questionlabel = ["labelid", setlabel.value];
    }
    loading.value = true;
    const { count, rows } = await asyncselectquestion(obj);
    questionData.value = rows;
    totalCount.value = count;
    loading.value = false;
  }, 300);
}
function start() {
  if (debouncet1.value) {
    debouncet1.value();
  }
}

function formDifficultyclick(item: string) {
  if (!Array.isArray(formInline.difficulty)) formInline.difficulty = [];
  const i = formInline.difficulty.findIndex((e: string) => e === item);
  if (i != -1) {
    formInline.difficulty.splice(i, 1);
  } else {
    formInline.difficulty.push(item);
  }
}
const cfDifficulty = ref("");
function sourceClick(item: string) {
  formInline.source = item;
}

function changePage(r: number) {
  offset.value = (r - 1) * limit.value;
  start();
}
const handleSizeChange = (val: number) => {
  limit.value = val;
  start();
};

async function del(ID?: number) {
  if (ID) {
    ElMessageBox.confirm("你确定要删除此题吗", "提示").then(async () => {
      try {
        await asyncdelquestion({ ID });
        ElMessage.success("删除成功");
        start();
      } catch (e: any) {
        ElMessage.error(e);
      }
    });
  }
}

// 添加题目
const dialogVisibleAddQuestion = ref(false);
async function addclick(v: Studycodemodel.Iquestionbank) {
  await asyncaddquestionteam({ questionid: v.ID, teamid: teamId.value })
    .then(() => {
      ElMessage.success("添加成功");
      dialogVisibleAddQuestion.value = false;
    })
    .catch((f) => {
      ElMessage.error(f);
    });
}
function beforeClose() {
  start();
  dialogVisibleAddQuestion.value = false;
}
</script>

<style scoped>
.container-box {
  /* 是否固定表格列表 */
  min-height: calc(100vh - 90px);
  /* max-height: calc(100vh - 90px); */

  /* margin-top: 20px; */
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 23vh;
  --container-bg-color: #fff;
}

.container-left {
  margin-right: var(--container-margin);
}

.container-header {
  width: 100%;
  padding: 0;
}

.container-header-form {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  /* height: calc(var(--container-header-height) - var(--el-tabs-item-height)); */
  height: auto;
  padding: 10px 0 15px 0;
}

.container-header-form-item {
  font-weight: 700;
  text-align: left;
  margin: 10px 0;
  --color-43: #000;
}

.container-header-form-item .el-button.is-text {
  border-width: 1px;
}

.container-header-form-item .el-button--default:active {
  border-color: transparent;
}

.container-header-form-item-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.container-content {
  margin-top: var(--container-margin);
  background: var(--container-bg-color);
  padding: var(--container-margin);
  min-width: 80%;
}

.container-content .pager {
  margin: var(--container-margin);
  margin-right: 0;
  margin-bottom: 0;
  float: right;
}

.container-aside {
  min-width: 25%;
  background: var(--container-bg-color);
}
</style>

<style>
.el-button.is-text {
  border-width: 1px;
}
</style>
